package com.dries.portal.module.coupon.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dries.common.api.CommonResult;
import com.dries.portal.module.coupon.enums.TemplateStatus;
import com.dries.common.exception.ApiException;
import com.dries.portal.module.coupon.entity.Template;
import com.dries.portal.module.coupon.form.AddTemplateForm;
import com.dries.portal.module.coupon.service.ICouponService;
import com.dries.portal.module.coupon.service.ITemplateService;
import com.dries.portal.module.coupon.vo.CouponTemplateRecord;
import com.dries.portal.module.coupon.vo.CouponTemplateSDK;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 优惠券模板表
 *
 * @author dries
 * @email samphsanie@gmail.com
 * @date 2020-07-27 13:06:07
 */
@Slf4j
@Api(tags = "优惠券API", value = "TemplateController")
@RestController
@RequestMapping("/coupon/template")
public class TemplateController {

    @Resource
    private ITemplateService templateService;
    @Resource
    private ICouponService couponService;

    @ApiOperation(value = "构建优惠券模板")
    @PostMapping("/create")
    public CommonResult buildTemplate(@RequestBody AddTemplateForm form) {

        templateService.buildTemplate(form);

        return CommonResult.success("创建优惠券模板成功");
    }

    @ApiOperation(value = "获取优惠券模板详情")
    @GetMapping("/info/{id}")
    public CommonResult buildTemplateInfo(@PathVariable("id") Integer id) {

        Template info = templateService.getTemplateInfoById(id);
        if (info != null) {
            return CommonResult.success(info);
        } else {
            return CommonResult.failed("没用查询到优惠券信息");
        }

    }

    @ApiOperation(value = "查找所有可用的优惠券模板")
    @GetMapping("/sdk/all")
    public CommonResult findAllUsableTemplate() {
        log.info("Find All Usable Template.");
        List<CouponTemplateSDK> sdks = templateService.findAllUsableTemplate();
        return CommonResult.success(sdks);
    }

    @ApiOperation(value = "查找所有可用的抵扣优惠券模板")
    @GetMapping("/sdk/all/deduction")
    public CommonResult findAllDeductionUsableTemplate() {
        log.info("Find All Usable Template.");
        List<CouponTemplateSDK> sdks = templateService.findAllDeductionUsableTemplate();
        return CommonResult.success(sdks);
    }

    @ApiOperation(value = "获取模板 ids 到 CouponTemplateSDK 的映射")
    @GetMapping("/sdk/infos")
    public CommonResult findIds2TemplateSDK(@RequestParam("ids") Collection<Integer> ids) {
        Map<Integer, CouponTemplateSDK> idsTemplateSDK = templateService.findIdsTemplateSDK(ids);
        return CommonResult.success(idsTemplateSDK);
    }

    @ApiOperation(value = "获取店铺发布的优惠券模板")
    @GetMapping("/shop/{shopId}")
    public CommonResult getShopTemplate(@PathVariable("shopId") String shopId) {

        List<Template> templates = templateService.list(new QueryWrapper<Template>().lambda()
                .eq(Template::getShopId, shopId)
                .eq(Template::getIsDelete, 0)
                .orderByDesc(Template::getCreateTime)
        );

        return CommonResult.success(templates);
    }

    @ApiOperation(value = "获取优惠券模板使用记录")
    @GetMapping("/record/{templateId}")
    public CommonResult templateRecord(@PathVariable("templateId") String templateId) {

        CouponTemplateRecord record = templateService.getTemplateRecordByShopId(templateId);

        return CommonResult.success(record);
    }

    @ApiOperation(value = "上线优惠券模板")
    @GetMapping("/online/{templateId}")
    public CommonResult onlineTemplate(@PathVariable("templateId") String templateId) {

        Template byId = templateService.getOne(new QueryWrapper<Template>().lambda()
                .eq(Template::getId, templateId)
                .eq(Template::getIsDelete, 0)

        );
        if (byId == null) {
            throw new ApiException("该优惠券模板不存在");
        }
        boolean update = templateService.update(new UpdateWrapper<Template>().lambda()
                .set(Template::getAvailable, TemplateStatus.ON_LINE.getCode())
                .eq(Template::getId, templateId)
        );

        if (update) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @ApiOperation(value = "下架优惠券模板")
    @GetMapping("/offline/{templateId}")
    public CommonResult offlineTemplate(@PathVariable("templateId") String templateId) {

        Template byId = templateService.getOne(new QueryWrapper<Template>().lambda()
                .eq(Template::getId, templateId)
                .eq(Template::getIsDelete, 0)

        );
        if (byId == null) {
            throw new ApiException("该优惠券模板不存在");
        }
        boolean update = templateService.update(new UpdateWrapper<Template>().lambda()
                .set(Template::getAvailable, TemplateStatus.OFF_LINE.getCode())
                .eq(Template::getId, templateId)
        );

        if (update) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }
    
    @ApiOperation(value = "删除优惠券模板")
    @DeleteMapping ("/delete/{templateId}")
    public CommonResult deleteTemplate(@PathVariable("templateId") String templateId) {

        Template byId = templateService.getOne(new QueryWrapper<Template>().lambda()
                .eq(Template::getId, templateId)
                .eq(Template::getIsDelete, 0)

        );
        if (byId == null) {
            throw new ApiException("该优惠券模板不存在");
        }
        if (byId.getAvailable() == 1) {
            throw new ApiException("该优惠券模板已上架,操作失败");
        }

        boolean result = templateService.update(new UpdateWrapper<Template>().lambda()
                .set(Template::getIsDelete, 1)
                .set(Template::getAvailable, TemplateStatus.OFF_LINE.getCode())
                .eq(Template::getId, templateId)
        );

        if (result) {
            return CommonResult.success();
        }

        return CommonResult.failed();

    }

}
